﻿Imports System.Data
Imports VSModel
Imports Cls_Common
Imports SecurityService
Partial Class Control_Store_Edit
    Inherits System.Web.UI.UserControl
    'Luu nhung MenuId duoc check
    Private IDChecked As String = ""
    Private dtListMenuSelect As List(Of Category)
    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
#Region "Sub and Function "
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim script As ScriptManager = ScriptManager.GetCurrent(Me.Page)
            If Not script Is Nothing AndAlso script.IsInAsyncPostBack Then
                ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "duyjs", "ajaxJquery()", True)
            Else
                Me.Page.ClientScript.RegisterStartupScript(Me.Page.GetType(), "duyjs", String.Concat("Sys.Application.add_load(function(){", "ajaxJquery()", "});"), True)
            End If
            LoadType()
            FillParentMenu()
            ' getTemplate()

            If Not Request.QueryString("Storeid").ToString.Equals("0") Then
                hidID.Value = Request.QueryString("Storeid")
                ShowData()
            End If
        End If
    End Sub
    'Protected Sub getTemplate()
    '    ddlTemplate.Items.Clear()
    '    ddlTemplate.AppendDataBoundItems = True
    '    ddlTemplate.Items.Add(New ListItem("---Chọn---", "0"))
    '    Using data As New VSEntities
    '        Dim p = (From q In data.Templates Select q.TemplateId, q.Title).ToList
    '        ddlTemplate.DataValueField = "TemplateId"
    '        ddlTemplate.DataTextField = "Title"
    '        ddlTemplate.DataSource = p
    '        ddlTemplate.DataBind()
    '        ddlTemplate.SelectedValue = 0
    '    End Using

    'End Sub
    'Load du lieu cho menu cha
    Protected Sub FillParentMenu()
        Using data As New VSEntities
            Dim query = From q In data.Categories Where q.ParentId = 0 Order By q.Sort Ascending Select q
            Dim dtList = query.ToList()
            trvMenu.Nodes.Clear()
            For i As Integer = 0 To dtList.Count - 1
                Dim tnParent As New TreeNode()
                tnParent.Text = dtList(i).Title
                tnParent.Value = dtList(i).CatId.ToString()
                trvMenu.Nodes.Add(tnParent)
                tnParent.Collapse()
                ' FillChild(tnParent, Int32.Parse(tnParent.Value))
                If CheckSelectedMenu(dtListMenuSelect, dtList(i).CatId) = 1 Then
                    tnParent.Checked = True
                    tnParent.ExpandAll()
                Else
                    tnParent.Checked = False
                End If
            Next
        End Using
    End Sub
    'Load du lieu cho menu con
    Protected Sub FillChild(ByVal Parent As TreeNode, ByVal Value As Integer)
        Using data As New VSEntities
            Dim query = From q In data.Categories Where q.ParentId = Value Order By q.Sort Ascending Select q
            Dim dtList = query.ToList()
            Parent.ChildNodes.Clear()
            For i As Integer = 0 To dtList.Count - 1
                Dim child As New TreeNode()
                child.Text = dtList(i).Title
                child.Value = dtList(i).CatId.ToString()
                Parent.ChildNodes.Add(child)
                child.Collapse()
                FillChild(child, Int32.Parse(child.Value))
                If CheckSelectedMenu(dtListMenuSelect, dtList(i).CatId) = 1 Then
                    child.Checked = True
                    child.ExpandAll()
                End If
            Next
        End Using
    End Sub
    'Lay gia tri menu con
    Protected Sub GetChildNode(ByVal tn As TreeNode)
        For i As Integer = 0 To tn.ChildNodes.Count - 1
            If tn.ChildNodes(i).Checked = True Then
                IDChecked = (IDChecked & ",") + tn.ChildNodes(i).Value
            End If
            GetChildNode(tn.ChildNodes(i))
        Next
    End Sub
    'Lay gia tri menu con
    Protected Sub GetParentNode()
        IDChecked = ""
        For i As Integer = 0 To trvMenu.Nodes.Count - 1
            If trvMenu.Nodes(i).Checked = True Then
                IDChecked = (IDChecked & ",") + trvMenu.Nodes(i).Value
            End If
            GetChildNode(trvMenu.Nodes(i))
        Next

    End Sub

    Protected Function CheckSelectedMenu(ByVal dtList As List(Of Category), ByVal Value As Integer) As Integer
        Dim Result As Integer = 0
        If Not dtList Is Nothing Then
            For i As Integer = 0 To dtList.Count - 1
                If Int32.Parse(dtList(i).CatId.ToString()) = Value Then
                    Result = 1
                    Exit For
                End If
            Next
        End If
        Return Result
    End Function
    Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs)
        If trvMenu.CheckedNodes.Count > 0 Then
            args.IsValid = True
        Else
            args.IsValid = False
        End If
    End Sub

    Protected Sub LoadType()
        Using data As New VSEntities
            'Khu vuc
            ddlTinhTP.AppendDataBoundItems = True
            ddlTinhTP.Items.Insert(0, New ListItem("---Chọn---", "0"))
            Dim ba = (From ca In data.DonViHanhChinhs Select ca.Id, ca.Title).ToList
            ddlTinhTP.DataTextField = "Title"
            ddlTinhTP.DataValueField = "ID"
            ddlTinhTP.DataSource = ba
            ddlTinhTP.DataBind()

            Dim p = (From q In data.Users Where q.Vip = 3 And q.ApproveVip = True Order By q.UserName Select q.UserId, q.UserName).ToList
            With ddlNguoiDung
                .DataSource = p
                .DataTextField = "UserName"
                .DataValueField = "UserId"
                .DataBind()
                .Items.Insert(0, New ListItem("---Chọn---", "0"))
            End With

        End Using
    End Sub

    Protected Sub ShowData()
        Using data As New VSEntities
            Dim p As Store = (From q In Data.Stores Where q.StoreId = hidID.Value Select q).SingleOrDefault
            If Not p Is Nothing Then
                txtTitle.Text = IIf(IsNothing(p.Title) = True, "", p.Title)
                txtDescription.Text = IIf(IsNothing(p.Description) = True, "", p.Description)

                txtContactus.Text = IIf(IsNothing(p.ContactUs) = True, "", p.ContactUs)

                txtUrlweb.Text = IIf(IsNothing(p.URLWEB) = True, "", p.URLWEB)
                txtEmail.Text = IIf(IsNothing(p.Email) = True, "", p.Email)
                hidImagePath.Text = IIf(IsNothing(p.ImgLogo) = True, "", p.ImgLogo)
                imgUpload.ImageUrl = IIf(IsNothing(p.ImgLogo) = True, "", p.ImgLogo)
                hidImagePathBigbanner.Text = IIf(IsNothing(p.BigBanner) = True, "", p.BigBanner)
                imgUpload_bigbanner.ImageUrl = IIf(IsNothing(p.BigBanner) = True, "", p.BigBanner)

                txtSkypeid.Text = IIf(IsNothing(p.SkypeId) = True, "", p.SkypeId)
                txtSlogan.Text = IIf(IsNothing(p.Slogan) = True, "", p.Slogan)
                txtYahooid.Text = IIf(IsNothing(p.YahooId) = True, "", p.YahooId)

                ddlTinhTP.SelectedValue = IIf(IsNothing(p.TinhThanhId) = True, "0", p.TinhThanhId)
                txtDiachi.Text = IIf(IsNothing(p.DiaChi) = True, "", p.DiaChi)
                txtHoTen.Text = IIf(IsNothing(p.HoTen) = True, "", p.HoTen)
                txtPhone.Text = IIf(IsNothing(p.Phone) = True, "", p.Phone)
                txtPhoneOrther.Text = IIf(IsNothing(p.PhoneOther) = True, "", p.PhoneOther)
                ddlNguoiDung.SelectedValue = p.UserId
                txtMap.Text = IIf(IsNothing(p.Map) = True, "", p.Map)

                If Not p.IsVip Is Nothing Then
                    chkVIP.Checked = p.IsVip
                End If
                If Not p.IsNewCar Is Nothing Then
                    chkXeMoi.Checked = p.IsNewCar
                End If
                If Not p.IsOldCar Is Nothing Then
                    chkXeCu.Checked = p.IsOldCar
                End If

                Dim _StoreId As Integer = p.StoreId
                Dim arr = (From k In data.StoreTypes Where k.StoreID = _StoreId Select k.RootCateId).ToArray
                dtListMenuSelect = (From g In data.Categories Where arr.Contains(g.CatId) Select g).ToList
                FillParentMenu()


                Dim strImage As String = ""
                Dim t = (From a In data.StoreImages Where a.StoreId = p.StoreId Select a.StoreId, a.ImageURL, a.Description).ToList
                If Not t Is Nothing Then
                    For i As Integer = 0 To t.Count - 1
                        strImage += "showImage('" + i.ToString + "','" + t.Item(i).ImageURL.ToString + "','" + t.Item(i).Description.ToString + "');"
                    Next
                End If
                Excute_Javascript(strImage, Me.Page, True)
            End If
        End Using
    End Sub
#End Region
#Region "Event for control"
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Dim arrImage() As String = hidStrImage.Text.Trim.Split(",")
        Dim arrDest() As String = hidStrCommnet.Text.Trim.Split(";")
        Using data As New VSEntities
            Dim p As Store = (From q In data.Stores Where q.StoreId = hidID.Value).SingleOrDefault
            Try
                p.StoreId = hidID.Value
                p.Title = txtTitle.Text.Trim()
                p.QueryString = makeURLFriendly(txtTitle.Text.Trim)
                p.Description = txtDescription.Text.Trim()

                p.URLWEB = txtUrlweb.Text.Trim()
                p.Email = txtEmail.Text.Trim()
                p.ImgLogo = hidImagePath.Text.Trim
                p.UserId = ddlNguoiDung.SelectedValue
                p.SkypeId = txtSkypeid.Text.Trim()
                p.Slogan = txtSlogan.Text.Trim()
                p.YahooId = txtYahooid.Text.Trim()
                p.TinhThanhId = ddlTinhTP.SelectedValue
                p.DiaChi = txtDiachi.Text.Trim
                p.HoTen = txtHoTen.Text.Trim
                p.Phone = txtPhone.Text.Trim
                p.PhoneOther = txtPhoneOrther.Text.Trim
                p.IsVip = chkVIP.Checked
                p.IsNewCar = chkXeMoi.Checked
                p.IsOldCar = chkXeCu.Checked

                p.Map = txtMap.Text
                p.BigBanner = hidImagePathBigbanner.Text
                p.ContactUs = txtContactus.Text.Trim()
                data.SaveChanges()

                'add images
                If p.StoreId > 0 Then
                    Dim t As List(Of StoreImage) = (From h In data.StoreImages Where h.StoreId = hidID.Value Select h).ToList
                    For Each h As StoreImage In t
                        data.StoreImages.DeleteObject(h)
                    Next
                    For i As Integer = 0 To arrImage.Length - 2
                        Dim b As New StoreImage
                        b.Description = arrDest(i).ToString
                        b.ImageURL = arrImage(i).ToString
                        b.StoreId = p.StoreId
                        data.StoreImages.AddObject(b)
                    Next
                End If


                'Add cho Loai store
                GetParentNode()
                Dim arrID() As String = IDChecked.Split(",")
                If arrID.Length > 0 Then
                    'Xoa du lieu cu
                    Dim h As List(Of VSModel.StoreType) = (From t In data.StoreTypes Where t.StoreID = p.StoreId Select t).ToList
                    For Each k As VSModel.StoreType In h
                        data.StoreTypes.DeleteObject(k)
                        data.SaveChanges()
                    Next
                    For i As Integer = 1 To arrID.Length - 1
                        Dim k As New VSModel.StoreType
                        k.StoreID = p.StoreId
                        k.RootCateId = arrID(i)
                        data.StoreTypes.AddObject(k)
                        data.SaveChanges()
                        k = Nothing
                    Next
                End If


                
                Insert_App_Log("Update Store:" & txtTitle.Text.Trim & "", Function_Name.Store, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                Excute_Javascript("Alertbox('Cập nhật dữ liệu thành công.');window.location ='../../Page/Store/List.aspx';", Me.Page, True)

            Catch ex As Exception
                log4net.Config.XmlConfigurator.Configure()
                log.Error("Error error " & AddTabSpace(1) & Session("Username") & AddTabSpace(1) & "IP:" & GetIPAddress(), ex)
                Excute_Javascript("Alertbox('Cập nhật thất bại.');", Me.Page, True)
            End Try
        End Using
    End Sub
    Protected Sub btnHuy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHuy.Click
        Response.Redirect("List.aspx")
    End Sub
#End Region
End Class
